package encservice

import (
	"gmap-backend/internal/config"
	"gmap-backend/internal/server/vo"
	"gmap-backend/internal/util/encodeutil"
)

const DefaultDecryptErrMsg = "内容无法解密"

func Encrypt(appConfig *config.AppConfig, req *vo.TxtReq, bins [][]byte) *vo.TxtResp {
	encodedTxt := encodeutil.EncryptSm4(req.Txt, appConfig.SecretConfig.Sm4Key)
	return &vo.TxtResp{Txt: encodedTxt}
}

func Decrypt(appConfig *config.AppConfig, req *vo.TxtReq, bins [][]byte) *vo.TxtResp {
	originTxt := encodeutil.DecryptSm4(req.Txt, appConfig.SecretConfig.Sm4Key)
	return &vo.TxtResp{Txt: originTxt}
}

func DecryptBatch(appConfig *config.AppConfig, req *vo.TxtsReq, bins [][]byte) *vo.TxtsResp {
	size := len(req.Txts)
	result := make([]string, size)
	for i, encoded := range req.Txts {
		result[i] = decryptItem(encoded, appConfig.SecretConfig.Sm4Key)
	}
	return &vo.TxtsResp{Txts: result}
}

func decryptItem(encoded string, key string) (result string) {
	defer func() {
		if err := recover(); err != nil {
			result = DefaultDecryptErrMsg
		}
	}()
	return encodeutil.DecryptSm4(encoded, key)
}
